from django.shortcuts import render,redirect
from django.http import HttpResponse
from Bio import SeqIO
from io import StringIO
from Bio import SeqIO
import re
from io import StringIO
import json
from django.views.decorators.csrf import csrf_exempt
from wen import lib
import re
import joblib
@csrf_exempt

def predict_peptide(request):

    json_orfs=json.loads(request.POST['orf_info'])
    for orf in json_orfs:
        print(orf)
        xulie=orf['xulie']
        seq=str(xulie)
        seq=re.sub(r'[^ATCGatcg]','',seq)
        seq=seq.upper()
        if seq.__len__()%3!=0:
            orf['peptide'] = 'no'
        else:
            tezheng = []
            seq = str(seq)[0:-3]
            codon_length = seq.__len__()
            codon, feat = lib.get_features()
            for i in range(0, codon_length, 3):
                feat[seq[i:i + 3]] = feat[seq[i:i + 3]] + 1
            for cod in codon:
                tezheng.append(round(feat[cod] / (codon_length / 3), 5))
            clf=joblib.load('wen/clf.pkl')
            pre=clf.predict([tezheng])
            # print(tezheng)
            # print(pre)
            if pre==1:
                orf['peptide']='yes'
            else:
                orf['peptide']='no'

    return render(request,'peptide.html',{'json_orfs':json_orfs})
def peptide_predict(request):
    return render(request,'peptide_predict.html',{})
